package cn.com.jrj.hqquery.utils;

import java.util.NoSuchElementException;
/**
 * A looping list
 * @author peng.liu
 * @create 2011-1-17
 */
public class LoopingList<E> {

	private transient Entry<E> header = new Entry<E>(null, null, null);
	private transient int size = 0;
	private int capacity = 0;

	private static class Entry<E> {
		E element;
		Entry<E> next;
		Entry<E> previous;

		Entry(E element, Entry<E> next, Entry<E> previous) {
			this.element = element;
			this.next = next;
			this.previous = previous;
		}
	}

	/**
	 * Constructs an empty list.
	 */
	public LoopingList(int initCapacity) {
		capacity = initCapacity;
		header.next = header.previous = header;
	}

	/**
	 * Inserts the given element at the beginning of this list.
	 * 
	 * @param o
	 *            the element to be inserted at the beginning of this list.
	 */
	public void putFirst(E o) {
		putAfter(o, header);
	}

	private Entry<E> putAfter(E o, Entry<E> e) {
		Entry<E> newEntry = null;
		if (size == 0) {
			header.element = o;
			newEntry = header;
			size++;
		} else {
			if (size < capacity) {
				newEntry = new Entry<E>(o, e.next, e);
				newEntry.previous.next = newEntry;
				newEntry.next.previous = newEntry;
				size++;
			} else {
				newEntry = header.next;
				newEntry.element = o;
			}
			header = header.next;
		}

		return newEntry;
	}

	/**
	 * Returns the first element in this list.
	 * 
	 * @return the first element in this list.
	 * @throws NoSuchElementException
	 *             if this list is empty.
	 */
	public E getFirst() {
		if (size == 0)
			return null;

		return header.element;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		Entry<E> entry = header;
		for (int i = 0; i < size; i++, entry = entry.previous) {
			sb.append(entry.element).append(" ");
		}
		return sb.toString();
	}
	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		int size = 10;
		LoopingList<Integer> list = new LoopingList<Integer>(size);
		for (int i = 1; i <= 50; i++) {
			list.putFirst(i);
			System.err.println(list.getFirst());
		}
	}
}
